from rest_framework import serializers
from base_utils.serializer import ModelSerializer, Serializer
from . import models
from base_utils.exception import ParamsError
from base_utils.redis_pool import get_redis_client
from lua_script.seconds_kill import SeckillService
from base_utils.response_http_code import SuccessStatus, BadRequestStatus


# 秒杀的流程
class SecondKillSer(Serializer):
    user_id = serializers.IntegerField()
    goods_id = serializers.IntegerField()

    def validate(self, attrs):
        goods_id = attrs.get("goods_id")
        exist = models.GoodsModel.objects.filter(id=goods_id).count()
        if not exist:
            raise ParamsError("不存在此商品")
        return attrs

    def create(self, validated_data):
        user_id = validated_data.get("user_id")
        goods_id = validated_data.get("goods_id")
        redis_client = get_redis_client()
        obj = SeckillService(redis_client)
        is_true, inventory = obj.seckill_with_lua(goods_id, user_id)
        if is_true:
            code = SuccessStatus.http_code
        else:
            code = BadRequestStatus.http_code
        return {"code": code, "msg": inventory}
